package com.lxl.controller;

import com.lxl.entity.User;
import com.lxl.service.IService;
import com.lxl.service.impl.UserServiceImpl;
import com.lxl.utils.VerifyCodeUtil;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 北上寻海
 */
@WebServlet({"/login","/verifyCode","/exit"})

public class UserServlet extends BaseServlet {
    IService userService = new UserServiceImpl();
    final static String LOGIN_IN_FREE = "free";
    /**
     * 添加用户
     * @param user 待添加用户的信息
     */
    public void addUser(User user){

        try {
            int result = userService.addUser(user);
            System.out.println(result>0?"添加成功":"添加失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List findById(Object[] params){

        List list =null;
        try {
           list = userService.findById(params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public List findAll(){

        List list =null;
        try {
            list = userService.findAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }


    public void deleteById(int id){
        try {
           int result =  userService.deleteUserById(id);
            System.out.println(result>0?"删除成功":"删除失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateById(Object[] params){
        try {
            int result =  userService.updateUserById(params);
            System.out.println(result>0?"更新成功":"更新失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void  getVerifyCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将验证码存入session会话域
        String verifyCode = VerifyCodeUtil.getVerifyCode(4);
        HttpSession session = request.getSession();
        session.setAttribute("verifyCode",verifyCode);
        //将验证码放进图片，流输出图片
        response.setContentType("image/jpeg");
        ServletOutputStream os = response.getOutputStream();
        VerifyCodeUtil.outputImage(os,verifyCode);
    }



    public void login (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        List list =null;
        String username=request.getParameter("username");
        String password = request.getParameter("password");
        String loginInFree = request.getParameter("loginInFree");
        try {
            list = userService.verify(username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //拿出存在session会话域的验证码和前端页面发过来的验证码作比较
        HttpSession session = request.getSession();
        String verifyCode1 = (String) session.getAttribute("verifyCode");
        String verifyCode2 = request.getParameter("verifyCode");
        if(list!=null){
            if(verifyCode1.equalsIgnoreCase(verifyCode2)) {
                //已经登录信息在这里存进session域
                User user = new User(username,password);
                session.setAttribute("user",user);

                //七天免登录在这里写
                //cookie存储登录状态，setMaxAge设置存活时间，cookie文件存到硬盘文件中
                //设置cookie访问路径，只要是访问这个项目就要携带这两个cookie
                //将cookie响应给浏览器
                if(LOGIN_IN_FREE.equals(loginInFree)){
                    Cookie cookie1 = new Cookie("username",username);
                    Cookie cookie2 = new Cookie("password",password);
                    cookie1.setMaxAge(3600*24*7);
                    cookie2.setMaxAge(3600*24*7);
                    cookie1.setPath(request.getContextPath());
                    cookie2.setPath(request.getContextPath());
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                response.sendRedirect(request.getContextPath() + "commonStaffWork.jsp");
                }
            }else {
                request.setAttribute(request.getContextPath()+"errorData2","验证码输入有误");
                request.getRequestDispatcher(request.getContextPath()+"index.jsp").forward(request,response);
            }
        }else {
            request.setAttribute(request.getContextPath()+"errorData1","用户名或密码不正确");
            request.getRequestDispatcher(request.getContextPath()+"index.jsp").forward(request,response);
        }
    }

    public void  exit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //删除十天免登录的Cookie
        Cookie[] cookies =request.getCookies();
        if(cookies!=null){
            for(Cookie cookie : cookies){
                cookie.setMaxAge(0);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
        }
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }
}
